package xyz.cerberu.cet.spider.anime.spider.Logic;

import com.spider.core.ProcessLogic;
import com.spider.page.HtmlPage;
import com.spider.page.ResultPage;
import org.apache.ibatis.exceptions.PersistenceException;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.cerberu.cet.anime.dao.AnimeDao;
import xyz.cerberu.cet.anime.domain.Anime;

import java.sql.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;

/**
 * @author β世界
 * Created on 15:40
 * @Description 动漫的爬取逻辑
 */
@Component
public class AnimeLogic implements ProcessLogic {
    private static final Logger LOGGER = LoggerFactory.getLogger(AnimeLogic.class);
    private final AnimeDao animeDao;

    private static final String INTRODUCTION_REGEX = "//div[@id=\"subject_summary\"]";
    private static final String COVER_REGEX = "//*[@id=\"bangumiInfo\"]/div/div/a";
    private static final String URL_REGEX = "(https|http)://bgm.tv/subject/\\d+";

    @Autowired
    public AnimeLogic(AnimeDao animeDao) {
        this.animeDao = animeDao;
    }

    @Override
    public boolean isProcess(ResultPage resultPage) {
        // 判断是否为动漫主页
        if(resultPage.getUrl().toString().matches(URL_REGEX)) {return true ;}
        return false;
    }

    @Override
    public void logic(ResultPage resultPage) {
        HtmlPage page = (HtmlPage)resultPage;
        String url = page.getUrl().toString();
        // 获取动漫的信息
        List<Element> info = page.xpath("//ul[@id=\"infobox\"]/li");
        Anime anime = new Anime();

        for (Element value : info) {
            Elements element = value.select("span[class=tip]");

            // 获取标签名
            String tagName = element.text().trim();

            // 获取动漫名字
            if ("中文名:".equals(tagName)) {
                anime.setAnime_name(value.childNode(1).outerHtml());
                // 如果这个动漫本身就是国漫，就直接获取动漫原标题当做动漫名,如果说这个动漫没有中文名也一样
            } else if (anime.getAnime_name() == null) {
                anime.setAnime_name(page.xpath("//*[@id=\"headerSubject\"]/h1/a").get(0).text());
            }

            // 获取动漫别名
            if ("别名:".equals(tagName) && anime.getAlias() == null) {
                String alias = value.childNode(1).outerHtml();
                if(!"".equals(alias)){
                    anime.setAlias(alias);
                }
            }

            // 获取播放的时间
            if ("放送开始:".equals(tagName) || "上映年度:".equals(tagName) || "发售日:".equals(tagName)) {
                String update_time = value.childNode(1).outerHtml().trim();
                if (update_time.matches("\\d{4}[年-]\\d{1,2}[月-]\\d{1,2}[日]*")) {
                    update_time = update_time.replaceAll("[年月]", "-").replaceAll("[日]", "");
                    String[] time = update_time.split("-");
                    LocalDate localDate = LocalDate.of(Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2]));
                    anime.setUpdate_Time(new Date(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()));
                }
            }

            // 获取官方的网址
            if ("官方网站:".equals(tagName)) {
                anime.setWebsite(value.childNode(1).outerHtml());
            }

        }

        // 设置图片
        if(page.xpath(COVER_REGEX).size() != 0){
            anime.setCover("https:"+page.xpath(COVER_REGEX).get(0).attr("href"));
        }

        // 检查信息是否缺少
        if(anime.getUpdate_Time() != null && anime.getYear() != 0 && anime.getWeek() != 0 && anime.getCover() != null){
            try{
                // 设置动漫简介
                if(page.xpath(INTRODUCTION_REGEX).size() != 0){
                    anime.setIntroducation(page.xpath(INTRODUCTION_REGEX).get(0).text());
                }
                // 添加动漫封面链接
                if(page.xpath(COVER_REGEX).size() == 0){
                    throw new PersistenceException();
                }
                anime.setAnime_url();
                // 根据bgm的ID进行计算
                anime.setAni_id(url.substring(url.lastIndexOf("/")+1));
                LOGGER.info(anime.toString());
                // 向数据库添加一个动漫
                animeDao.insertAnime(anime);
                LOGGER.info("添加动漫："+anime.getAnime_name()+" 更新时间："+anime.getUpdate_Time()+" bgm链接："+page.getUrl());
            }catch (Exception e){
                if(e instanceof PersistenceException){
                    LOGGER.warn(page.getUrl()+" 添加失败,缺失数据");
                }
                e.printStackTrace();
            }
        }else{
            LOGGER.info(page.getUrl()+"数据不全，不添加");
        }

    }
}
